package kliment.api.google
{
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;

	import kliment.api.ICheckout;
	import kliment.data.ShopingCartItem;

	/**
	 *
	 */
	public class GoogleCheckout implements ICheckout
	{
		static private const _devAPI_URL:String 	= "https://sandbox.google.com/checkout/api/checkout/v2/checkoutForm/Merchant/";
		static private const _API_URL:String 		= "https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/";

		/**
		 * Merchant ID
		 *
		 * @default 853989395876916 uses a Google public sandbox store.
		 */
		public var merchantID:String = "853989395876916";;

		/**
		 *
		 */
		public const currency:String = "USD";

		/**
		 * Development mode
		 */
		public var devMode:Boolean = false;

		private var _itemsCollection:Array = [];

		/**
		 * Constructor.
		 */
		public function GoogleCheckout()
		{

		}

		/**
		 * @inheritDoc
		 */
		public function get apiURL():String
		{
			if (devMode)
				return _devAPI_URL;
			return _API_URL;
		}

		/**
		 * @inheritDoc
		 */
		public function getRequestVariables():URLVariables
		{
			var urlVars:URLVariables = new URLVariables();
			urlVars._charset_ = "UTF-8";
			return urlVars;
		}

		/**
		 * @inheritDoc
		 */
		public function submit():Boolean
		{
			var length:uint = _itemsCollection.length;
			if (!length)
			{
				return false;
			}

			var urlVars:URLVariables = getRequestVariables();

			var item:Object;
			for (var i:uint = 0; i < length; i++)
			{
				item = _itemsCollection[i];
				for (var j in item)
				{
					urlVars[j] = item[j];
				}
			}

			var urlRequest:URLRequest = new URLRequest(apiURL + merchantID);
			urlRequest.method = URLRequestMethod.POST;
			urlRequest.data = urlVars;

			navigateToURL(urlRequest, "_blank");

			return true;
		}

		/**
		 * @inheritDoc
		 */
		public function attachProducts(list:Array):Boolean
		{
			var length:uint = list.length;
			_itemsCollection = [];

			if (length > 0)
			{
				for (var i:uint = 0; i < length; i++)
				{
					_itemsCollection.push(convertCardItem(list[i], i + 1));
				}
				return true;
			}
			return false;
		}

		private function convertCardItem(value:ShopingCartItem, index:uint = 0):Object {
			var result:Object = new Object();
			var suffix:String = '_' + index;
			result['item_number' + suffix] = value.id;
			result['item_price' + suffix] = value.price;
			result['item_name' + suffix] = value.name;
			result['item_description' + suffix] = value.description;
			result['item_quantity' + suffix] = value.quantity;
			result['item_currency' + suffix] = currency;;
			return result;
		}
	}

}